import React, {
    useEffect,
    useLayoutEffect,
    useState,
    useCallback,
    useMemo
} from "react";
import {
    message,
    Popover,
    Select,
    Pagination,
    ConfigProvider,
    Spin,
    Checkbox,
    Badge
} from "antd";
import {
    connect,
    useDispatch
} from "react-redux";
import zhCN from "antd/es/locale/zh_CN";
import axiosMethod from "../../../util/axios";
import "./index.scss";
import CONFIG from "../../../util/config";
import Search from "../../../common/component/search";
import Empty from "../../../common/component/empty";
import Modal from "../../../common/component/modal";
import {
    judgeJson
} from "../../../util";
import {
    LgPaginationA
} from 'lancoo-web-ui'
import Scrollbars from "react-custom-scrollbars";
import dayjs from 'dayjs'
import axios from "axios";
import GroupIcon from '../../../images/group.png'
const {
    appAddr
} = CONFIG;
const {
    Option
} = Select;


function Todo(props) {
    let {
        userInfo,
        sysAddrInfo,
        currentIdentity,
        sysInfo,
        alertInfo,
        chatList=[]
    } = props;
    const dispatch = useDispatch();
    const [chatAddr, setChatAddr] = useState("");

    const [selectList, setSelectList] = useState([]);

    const [loadVisible, setLoadVisible] = useState(false);
    const [socket, setSocket] = useState({});

    const [keyword, setKeyword] = useState("");

    const [hiddenVisible, setHiddenVisible] = useState(false);
    const [hiddenInfo, setHiddenInfo] = useState([]);
    const [sessionList, setSessionList] = useState([])

    const hiddenChange = useCallback((value) => {
        setHiddenVisible(value);
    }, []);
    const searchMethod = useCallback((value) => { //搜索函数
        setKeyword(value);
        window.chatsocket && window.chatsocket.send(JSON.stringify({
            msgType: 4,
            clientType: 5,
            token: sessionStorage.getItem('token'),
            data: {
                keyword: value
            }
        }))
    }, [userInfo, socket]);
    const goAddressBook = () => {
        window.getWebAddr('264', function (data) {
            window.open(data + '/homepage/web/index.html?lg_tk=' + sessionStorage.getItem('token') + '#/communication', '_blank')
        })
    }
    const getHiddenInfo = useCallback(() => { //获取屏蔽设置信息
        axios.request({
            type: "get",
            url: chatAddr + "/Chat/GetShieldList?UserID=" + userInfo.UserID,
            headers: {
                Authorization: "X-Token=" + sessionStorage.getItem('token')
            }
        }).then((res) => {
            let reuslt = res.data.Data
            reuslt && Array.isArray(reuslt.UserList) && setHiddenInfo(reuslt.UserList);
            setHiddenVisible(true);
        })
    }, [userInfo, chatAddr]);
    
    const selectNotice = useCallback((data, index, e) => {
        e.stopPropagation();
        let list = JSON.parse(JSON.stringify(selectList)),
            target = "";
        list.forEach((item, index) => {
            if (item.noticeId === data.noticeId) {
                target = index;
            }
        })
        if (typeof target === "number") {
            list.splice(target, 1);
        } else {
            list.push(data);
        }
        setSelectList(list);
    }, [selectList]);

    const setRead = useCallback((data, e) => { //设置免打扰
        e && e.stopPropagation();
        window.chatsocket && window.chatsocket.send(JSON.stringify({
            "msgType": "12",
            "clientType": "5",
            "token": sessionStorage.getItem('token'),
            "data": {
                "sessionId":data.sessionId,
                "remind": data.remind==0?1:0
            }
        }))
    }, []);

    const setSilent = useCallback((data, e) => { //设置屏蔽
        e && e.stopPropagation();

        // // 使用map方法遍历数组并修改对象
        // let modifiedObjects = sessionList.map(function(obj) {
        //   if (obj.sessionId === data.sessionId) {
        //     obj.block = obj.block==1?0:1;
        //   }
        //   return obj;
        // });

        // console.log(modifiedObjects)
        // setSessionList(modifiedObjects)

        window.chatsocket && window.chatsocket.send(JSON.stringify({
            "msgType": "11",
            "clientType": "5",
            "token": sessionStorage.getItem('token'),
            "data": {
                "sessionId":data.sessionId,
                "block": data.block==0?1:0
            }
        }))
    }, []);

    const setDelete = useCallback((data, e) => { //设置删除
                e && e.stopPropagation();
                dispatch({
                    type: "SET_ALERTINFO",
                    data: {
                        visible: true,
                        title: "是否移除该会话？",
                        onCancel: function () {
                            dispatch({
                                type: "SET_ALERTINFO",
                                data: {}
                            })
                        },
                        onOk: function () {
                            dispatch({
                                type: "SET_ALERTINFO",
                                data:{}
                            })
                            window.chatsocket && window.chatsocket.send(JSON.stringify({
                                "msgType": "7",
                                "clientType": "5",
                                "token": sessionStorage.getItem('token'),
                                "data": {
                                    "sessionId": data.sessionId,
                                }
                            }))
                        }
                    }
                });
    }, [dispatch]);

    const setRemove = useCallback((data) => {
        axios.request({
            type: "get",
            url: chatAddr + `/Chat/CancelShieldUser?SenderID=${userInfo.UserID}&CancelShieldUserID=${data.UserID}`,
            headers: {
                Authorization: "X-Token=" + sessionStorage.getItem('token')
            },
        }).then((res) => {
            message.success("移除成功");
            getHiddenInfo();
            socket.send(JSON.stringify({
                MessageType: 1200,
                ClientType: 41,
                Data: {
                    SenderID: userInfo.UserID,
                    SessionKeyword: keyword,
                    PageIndex: 1,
                    PageSize: 700
                }
            }))
        })
    }, [chatAddr, userInfo, getHiddenInfo, keyword, socket]);

    const removeShiled = (data) => {
        return new Promise((resolve, reject) => {
            axios.request({
                type: "get",
                url: chatAddr + `/Chat/CancelShieldUser?SenderID=${userInfo.UserID}&CancelShieldUserID=${data.UserID}`,
                headers: {
                    Authorization: "X-Token=" + sessionStorage.getItem('token')
                },
            }).then((res) => {
                resolve()
            }).catch(() => {
                reject()
            })
        })
    }

    const setRemoveAll = () => {
        if (hiddenInfo.length < 1) {
            message.warn('没有需要移除屏蔽的会话')
            return
        }

        dispatch({
            type: "SET_ALERTINFO",
            data: {
                visible: true,
                title: "是否清空屏蔽列表？",
                onCancel: function () {
                    dispatch({
                        type: "SET_ALERTINFO",
                        data: {}
                    })
                },
                onOk: function () {
                    let fetchArr = []
                    for (let i = 0; i < hiddenInfo.length; i++) {
                        const data = hiddenInfo[i];
                        fetchArr.push(removeShiled(data))
                    }
                    Promise.all(fetchArr).then(() => {
                        dispatch({
                            type: "SET_ALERTINFO",
                            data: {}
                        })
                        message.success("移除成功");
                        getHiddenInfo();
                        socket.send(JSON.stringify({
                            MessageType: 1200,
                            ClientType: 41,
                            Data: {
                                SenderID: userInfo.UserID,
                                SessionKeyword: keyword,
                                PageIndex: 1,
                                PageSize: 700
                            }
                        }))
                    })
                }
            }
        });

    }

    const getHtmlChat = (htmlString) => {
        var tempDiv = document.createElement('div');
        tempDiv.innerHTML = htmlString;
        var text = tempDiv.textContent;
        return text.trim()
    }

    const chatClick = useCallback((data) => {
        let newwindow=window.open()
        window.getWebAddr(460, function (webAddr) {
            let id = data.receiverId || data.groupId;
            let name = data.receiverName || data.receiverName;
            let session = data.sessionType || 1

            let chatUrl = webAddr + "/web/html/chat/index.html?lg_tk=" + sessionStorage.getItem("token") + "&lg_ic=" + currentIdentity.identityCode + '&receiverId=' + id + '&receiverName=' + name


            let sendObj= {
                "sessionType": session,
                "receiverId":id
            }

            if (session == 2) {
                sendObj = {
                    "sessionType": session,
                    "groupId": id
                }
            }

            if(window.chatsocket){
                window.chatsocket.send(JSON.stringify({
                    "msgType": "13",
                    "clientType": "5",
                    "token": sessionStorage.getItem('token'),
                    "data":sendObj
                }))
            }

            if (session == 2) {
                chatUrl = webAddr + "/web/html/chat/index.html?lg_tk=" + sessionStorage.getItem("token") + "&lg_ic=" + currentIdentity.identityCode + '&groupId=' + data.groupId + '&groupName=' + data.groupName + '&isGroup=1'
            }
            newwindow.location.href=chatUrl
        })
    }, []);

    const getSessionList = () => {
        if (window.chatsocket && window.chatsocket.readyState == 1) {
            window.chatsocket.send(JSON.stringify({
                "msgType": "4",
                "clientType": "5",
                "token": sessionStorage.getItem("token"),
                "data": {}
            }))
        }
    }


    useEffect(() => {
        getSessionList()
    }, []);



    return (
        <div className='main_chat'>
            <Spin spinning={loadVisible} tip="加载中...">
                <div className="chat_option">
                    <span className="list_info">共<span>{chatList.length}</span>条</span>
                    <span className="address_btn" onClick={goAddressBook}><i></i>查看通讯录</span>
                    {/* <span className="setting_btn" onClick={getHiddenInfo}><i></i>屏蔽设置</span> */}
                    <Search className="option_search" searchMethod={searchMethod} placeholder="搜索联系人姓名..." />
                </div>
                <Scrollbars
                    autoHeight
                    autoHeightMax={"calc(100vh - 290px)"}
                >
                    <div className="chat_list">
                        {
                            chatList.length > 0 ?
                                chatList.map((item, index) => {
                                    let receiverName=item.receiverName || item.groupName
                                    let sessionType=item.sessionType 
                                    let msgContent=getHtmlChat(item.lastMsg || '')

                                    return (
                                        <div className="chat_one" key={index} onClick={() => chatClick(item)}>
                                        {/* <Checkbox checked={item.check} onClick={(e)=>selectNotice(item, index, e)} /> */}
                                        <div className="one_header" style={{
                                            backgroundImage:sessionType==2?`url(${GroupIcon})`:item.receiverAvatarPath ? `url('${item.receiverAvatarPath}')` : ""
                        }
                    } > {
                        /* {
                                item.ReceiverOrGroupType === 0?
                                <span className="super_admin">超管</span>:
                                ""
                            } */}
                                        </div>
                                        <div className="one_info">
                                            <h4 className="info_name" title={receiverName}>
                                                <span className="name_text">{receiverName}</span>
                                                <span className="name_time">{item.updated&&item.lastMsg&&dayjs(item.updated).format('MM-DD HH:MM')}</span>
                                            </h4>
                                            <p className="info_detail" title={msgContent}>
                                                <span className="detail_name">
                                                    {msgContent}
                                                </span>
                                                <Badge
                                                    className="read_badge"
                                                    style={{ backgroundColor: item.remind==0 ? "#ccc" : "red" }}
                                                    size="small"
                                                    count={item.unReadCount} />

                                                {
                                                    item.block ?
                                                        <i className="silentlogo"></i> :
                                                        ""
                                                }
                                                {
                                                    item.remind==0&&!item.block ?
                                                        <i className="noreadlogo"></i> :
                                                        ""
                                                }
                                            </p>
                                        </div>
                                        <div className="one_option">
                                            {   item.block?"":
                                                item.remind === 0?
                                                    <>
                                                    <span className="blue_text" onClick={(e) => setRead(item, e)}>允许消息通知</span>
                                                    <span className="slice_line"></span>
                                                    </> :
                                                   <>
                                                    <span className="blue_text" onClick={(e) => setRead(item, e)}>消息免打扰</span>
                                                    <span className="slice_line"></span>
                                                   </>
                                            }
                                            {
                                               sessionType=== 1 ?
                                                    item.block === 1 ?
                                                        <>
                                                            <span className="blue_text" onClick={(e) => setSilent(item, e)}>取消屏蔽</span>
                                                        </> :
                                                        <>
                                                            <span className="blue_text" onClick={(e) => setSilent(item, e)}>屏蔽此人</span>
                                                        </> :
                                                    ""
                                            }
                                            <span className="slice_line"></span>
                                            <span className="red_text" onClick={(e) => setDelete(item, e)}>移除会话</span>
                                        </div>
                                    </div>
                                    )
                                }) :
                                <Empty text={'暂无交流信息'} style={{ marginTop: 160 }} />
                        }
                    </div>
                </Scrollbars>

                {/* <div className="chat_footer">
                    <div className="lg-skin-s2 pageOption" style={{ display: `${listTotal > 10 ? 'block' : 'none'}` }}>
                        <LgPaginationA
                            total={Math.ceil(listTotal / 10)}
                            size="normal"
                            currentPage={currentIndex}
                            onChangePage={(pageIndex) => {
                                setCurrentIndex(pageIndex);
                            }}
                        ></LgPaginationA>
                    </div>
                </div> */}
            </Spin>
            <Modal
                width={850}
                height={512}
                className="silent_modal"
                visible={hiddenVisible}
                changeVisible={hiddenChange}
                noFooter={true}
                title="在线交流屏蔽名单">
                <p className="silent_info">
                    共屏蔽<span>{hiddenInfo.length}</span>人
                    <span className="deletelogo" onClick={() => setRemoveAll()}>全部移除</span>
                </p>
                <div >
                    <div className="hidden_container">
                        {
                            hiddenInfo.map((item, index) => (
                                <span
                                    style={item.PhotoPath ? {
                                        backgroundImage: `url(${item.PhotoPath})`
                                    } : {}}
                                    className="silent_one"
                                    key={index}
                                >
                                    <i className="silent_header"></i>
                                    <span className="silent_name" title={
                                        `${item.UserName}(${item.UserID})`
                                    }>
                                        {item.UserName}
                                        <span style={{ color: "#999" }}>({item.UserID})</span>
                                    </span>
                                    <span className="deletelogo" onClick={() => setRemove(item)}>移除</span>
                                </span>
                            ))
                        }
                    </div>
                </div>
            </Modal>
        </div>
    )
}
const mapProps = (state) => {
    return {
        userInfo: state.userInfo,
        sysAddrInfo: state.sysAddrInfo,
        currentIdentity: state.currentIdentity,
        sysInfo: state.sysInfo,
        alertInfo: state.alertInfo
    }
}
export default connect(mapProps)(Todo);